package com.itita.ww2.game.user;

import java.util.HashMap;
import java.util.Map;

import com.itita.ww2.redis.RedisUtil;
import com.itita.ww2.redis.cache.Table;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.itita.ww2.model.army.UserArmy;
import com.itita.ww2.model.basemap.MapUnit;
import com.itita.ww2.model.user.UserProfile;

/**
 * 基地地图管理器(暂时废弃)
 * @author NorthLan
 *
 */
@Deprecated
public class UserBaseMapManager {
	private int uid;
	private UserProfile userProfile;
	private Map<String, MapUnit> userBaseMap;

	public UserBaseMapManager(UserProfile userProfile) {
		this.userProfile = userProfile;
		this.uid = userProfile.getUid();
		userBaseMap = new HashMap<>();
	}

	/**
	 * 添加固定建筑
	 */
	public synchronized void addBA(String code) {
		MapUnit mu = new MapUnit(code, SFSObject.newInstance());
		userBaseMap.put(code, mu);
	}

	/**
	 * 添加防御建筑
	 */
	public void addBD(String code, ISFSObject data) {
		MapUnit mu = new MapUnit(code, data);
		userBaseMap.put(code, mu);
		//		userProfile.getBDManager().getBDFortification().stockOper(mu.getBDCode(), 1, true);
		// 将其从兵营中丢出去
		userProfile.getArmyManager().armyCountOper(mu.getBDCode(), 1, false);
	}

	public synchronized void removeMapUnit(String code) {
		MapUnit mu = userBaseMap.remove(code);
		String bdCode = mu.getBDCode();
		//		userProfile.getBDManager().getBDFortification().stockOper(bdCode, 1, false);
		// 兵,则将其整回兵营中. 若满了,则销毁掉
		if (UserArmy.isArmy(bdCode)) {
			//			if (userProfile.getBDManager().getBDBarracks().isStockEnough(bdCode, 1)) {
			//				userProfile.getArmyManager().armyCountOper(bdCode, 1, true, true);
			//			}
		}
	}

	/**
	 * 获取地图单位
	 */
	public MapUnit getMapUnit(String code) {
		return userBaseMap.get(code);
	}

	/**
	 * 获取整个地图数据
	 */
	public ISFSObject getMapData() {
		ISFSObject ret = SFSObject.newInstance();
		for (MapUnit mu : userBaseMap.values()) {
			ret.putSFSObject(mu.getMapCode(), mu.toSFSObject());
		}
		return ret;
	}

	public synchronized void load() {
		Table t = UserService.getInstance().getCacheUserDataTable();
		ISFSObject mapdataObj = SFSObject.newFromJsonData(t.getValue(RedisUtil.genericKey(this.uid), "mapdata"));
		userBaseMap.clear();
		for (String mapcode : mapdataObj.getKeys()) {
			MapUnit mu = new MapUnit(mapcode, mapdataObj.getSFSObject(mapcode));
			userBaseMap.put(mapcode, mu);
		}
	}

	public synchronized void update() {
		ISFSObject ret = SFSObject.newInstance();
		for (MapUnit mu : userBaseMap.values()) {
			ret.putSFSObject(mu.getMapCode(), mu.toSFSObject());
		}
		Table t = UserService.getInstance().getCacheUserDataTable();
		t.setValue(RedisUtil.genericKey(this.uid), "mapdata", ret.toJson());
	}

	public synchronized void initialize() {
		this.update();
	}
}
